import gdb

class ListWithArrow(gdb.Command):
    def __init__(self):
        super(ListWithArrow, self).__init__("lar", gdb.COMMAND_FILES)

    def invoke(self, arg, from_tty):
        try:
            # 获取当前栈帧
            frame = gdb.selected_frame()
            # 获取当前执行的源文件和行号
            symtab_and_line = frame.find_sal()
            if symtab_and_line.symtab is None:
                print("No symbol table information available.")
                return
            current_line = symtab_and_line.line
            filename = symtab_and_line.symtab.filename
            # 打开源文件
            with open(filename, "r") as f:
                lines = f.readlines()
            # 确定要显示的行范围（当前行前后几行）
            start = max(0, current_line - 6)
            end = min(len(lines), current_line + 4)
            # 打印行号和代码
            for i in range(start, end):
                line_number = i + 1
                if line_number == current_line:
                    print(f"{line_number:4d} -> {lines[i].rstrip()}")
                else:
                    print(f"{line_number:4d}    {lines[i].rstrip()}")
        except Exception as e:
            print(f"An error occurred: {e}")

ListWithArrow()
